# -*- coding: utf-8 -*-
import md5, time, random
from os import environ
import re

from pycube.core import psql
from pycube.core.sql.model import column
from pycube.core.sql.types import *



#Session class***************************************************
class sess:
    def __init__ (self, environ, cookie ):
        
        
        
       
        self.psql = psql
        
        self.psql.register('testing',(
    
            column('id',     int8, autoSequence = True, primary_key = True, notnull = True, autoIndex = True ),        
            column('pid',    int2, notnull = True, autoIndex = True ), 
            column('title',  varchar(90) ),          
            column('fuck',   varchar(100) ),        
            column('published', bool, default = True), 
            column('fucking_row', varchar(50)),
            column('blah', date, default = 'now')
                
        ))
        
        
        self.environ = environ
        #Generating new session hash
        self.id = md5.new(str(time.time() + random.random())).hexdigest()
        
        self.lastEntrance = None
        self.done = False
        #generating new time
        
        self.cookie = cookie
        lt = time.localtime(time.time()+1200)
        self.time = "%04d-%02d-%02d %02d:%02d:%02d.%03d" % (lt[0], lt[1], lt[2], lt[3], lt[4], lt[5],lt[7])
        self.opera = False
        
        
        
    #Initialize session*******************************************    
    def start(self):
        #Getting cookies
        #write( environ )
        data = re.match( '.*?Opera.*?' , self.environ['HTTP_USER_AGENT'], re.DOTALL)
        if data:
            self.opera = True
         
        
        self.session_id = self.cookie.get('session_id')
        
        if self.session_id:
           
            result = self.psql.select( "SELECT name,user_id,expire,save,last_action FROM \"session\" WHERE expire > localtimestamp AND name =  %s", self.session_id, fetchall = True)
            
            if result: 
                #write(result[0][0])
                #Setting interval update, weather user checked to save his session
                self.lastEntrance = result[0][4]
                
                saveInterval = '336:00:00' if result[0][3] else '336:00:00'                              
                #Updating user's session
                self.psql.update("session", {
                    'expire'      : ["localtimestamp + '" + saveInterval+ "'::interval"],
                    'last_action' : ['localtimestamp']
                    
                }, "WHERE name = '%s'" % self.session_id )                
                self.psql.commit()
                
                if result[0][1]:
                   
                    r = self.psql.select("""SELECT u.id,u.login,u.email,u."group",                                  
                                 g.data FROM "users" u
                                 LEFT JOIN groups g on (u."group" = g.id) 
                                 WHERE u.id = %s""", result[0][1], fetchone = True )
                                   
                    try:                        
                        if r: 
                           data = {} 
                           #data = r[0]
                           data['user_auth'] = True
                           data['SID'] = self.session_id
                           
                           try:
                               perm = eval( r[4] )
                           except:
                               perm = {}
                           
                           data['permissions']=perm
                           data['user_login']=r[1]
                           data['user_id'] = r[0]
                           return data                    
                        else: 
                            
                           return self.default_result()
                    except:
                        return self.default_result()
               
                else: return self.default_result()
            else:
                #If no rows in database
                self.session_id =  self.cookie.set("session_id", self.id, 31104000)
                self.insert_sess()               
                
                return self.default_result()  
        else:          
            
            self.session_id =  self.cookie.set("session_id", self.id, 31104000) 
            if not self.opera:  
                self.insert_sess() 
          
            
            return self.default_result()           
    
    #Inserting new session        
    def insert_sess(self):
        
        self.psql.insert("session", {        
        'name'        : self.session_id,
        'expire'      : ["localtimestamp +  '00:20:00'::interval"],
        'last_action' : ['localtimestamp']
        })

        self.psql.commit()
    #Build default result. To get session at the same moment
    def default_result( self ):
        #print 'Content-Type: text/html\n'
        permissions = self.psql.select("SELECT data FROM \"groups\" WHERE name = 'guest'", fetchall = True)       
        if permissions:  
            #print permissions
            try:
                perm = eval( permissions[0][0] )
                perm = {'s':1}
            except:
                perm = {}
        else:
            perm = {}
        
        return {'SID':self.session_id,'user_auth':False,'permissions':perm,'user_id' : 0,'session_user_name':''}
      

    
    
    
    
        